'use strict';

const Service = require('egg').Service;
const path = require('path');
const fs = require('fs');
const ip = require('ip');
const dateFns = require('date-fns');
const qiniu = require('qiniu');
class FilesService extends Service {
  // ======================================================================  创建文件与文件夹  ======================================================================
  async create() {
    // =======================================  创建文件夹  =======================================
    const { ctx } = this;
    console.log(1212312312312312312)

    const stream = await ctx.getFileStream();
    const Infolder = ctx.request.header.folder;
    let folder = '';
    if (!Infolder || Infolder === 'undefined') {
      folder = dateFns.format(new Date(), 'yyyyMMddHHmmSS');
    } else {
      folder = Infolder;
    }
    const PH = path.join(ctx.app.config.baseDir, `app/public/comfiles/${folder}`); // 本地地址

    await new Promise(resolve => {
      fs.readdir(PH, (err: any) => {
        if (err) {
          fs.mkdir(PH, (err: any) => {
            if (err) { console.error(err); }
            console.log('创建目录成功');
            resolve('ok');
          });
        } else {
          resolve('ok');
        }
      });
    });
    console.log(999)
    // =======================================  保存图片  =======================================
    const _ip = '127.0.0.1';
    // const _ip = '47.99.84.138';
    const host = '7001';
    const _path = '/public/comfiles/';
    const filename = Date.now() + '' + Number.parseInt(String(Math.random() * 10000)) + path.extname(stream.filename); // 文件名称
    const returnDPath = `http://${_ip}:${host}${_path}${folder}/`; // 输出路径
    const target = path.join(ctx.app.config.baseDir, `app/public/comfiles/${folder}/${filename}`); // 保存路径


    const result = await new Promise((resolve, reject) => {
      const remoteFileStream = fs.createWriteStream(target);
      stream.pipe(remoteFileStream);
      let errFlag;
      remoteFileStream.on('error', err => {
        errFlag = true;
        remoteFileStream.destroy();
        reject(err);
      });
      remoteFileStream.on('finish', async () => {

        if (errFlag) {
          return
        }
        const NODE_ENV = process.env.NODE_ENV;

        // 上传七牛云;
        const result = await new Promise((resolve: any) => {
          console.log('09090909')
          const config = new qiniu.conf.Config();
          // 空间对应的机房
          config.zone = qiniu.zone.Zone_z0;
          const localFile = target;
          const formUploader = new qiniu.form_up.FormUploader(config);
          const putExtra = new qiniu.form_up.PutExtra();
          const key = `${NODE_ENV === 'development' ? 'dev-' : 'prod-'}${folder}-${Number.parseInt(
            String(Math.random() * 10000)
          )}`;
          // token凭证
          const data = ctx.service.sevFiles.getToken();
          formUploader.putFile(data.token, key, localFile, putExtra, (respErr, respBody, respInfo) => {
            console.log(respErr, respBody, respInfo)
            if (respErr) {
              throw respErr;
            }
            if (respInfo.statusCode === 200) {
              respBody.path = `${data.domain}/${respBody.key}`;
              console.log({ local: { path: returnDPath + filename, folder, name: filename }, qiniu: respBody })
              resolve({ local: { path: returnDPath + filename, folder, name: filename }, qiniu: respBody });
            } else {
              resolve({ local: { path: returnDPath + filename, folder, name: filename } });

            }
          });
        });
        console.log(123123123)
        // return result
        resolve(result);
      });
    });
    console.log('0000000', result)
    return result;
  }
  // // ======================================================================  删除文件夹  ======================================================================
  // removeFolder(folderName, _this) {
  //   const self = this || _this;
  //   const PH = path.join(self.config.baseDir, `app/public/comfiles/${folderName}`);// 本地地址

  //   new Promise(resolve => {
  //     if (fs.existsSync(PH)) {
  //       const files = fs.readdirSync(PH);
  //       files.forEach(file => {
  //         const curPath = PH + '/' + file;
  //         if (fs.statSync(curPath).isDirectory()) { // recurse
  //           fs.rmdirSync(PH);
  //           console.log('文件夹');
  //         } else { // delete file
  //           console.log('删除文件', file);
  //           fs.unlinkSync(curPath, err => {
  //             if (err) throw err;
  //           });
  //         }
  //       });
  //       fs.rmdirSync(PH);
  //       resolve();
  //     }
  //   });
  // }

  // ======================================================================  七牛云TOKEN  ======================================================================
  getToken() {
    const { ctx } = this;
    const mac = new qiniu.auth.digest.Mac(ctx.app.config.qiniu.ACCESS_KEY, ctx.app.config.qiniu.SECRET_KEY);

    const options = {
      scope: ctx.app.config.qiniu.name,
    };
    const putPolicy = new qiniu.rs.PutPolicy(options);
    const uploadToken = putPolicy.uploadToken(mac);

    return {
      domain: ctx.app.config.qiniu.domain,
      token: uploadToken,
    };
  }

  // // ======================================================================  获取七牛云文件列表  ======================================================================
  async getFileList() {
    const { ctx } = this;
    const mac = new qiniu.auth.digest.Mac(ctx.app.config.qiniu.ACCESS_KEY, ctx.app.config.qiniu.SECRET_KEY);
    const config = new qiniu.conf.Config();
    // config.useHttpsDomain = true;
    config.zone = qiniu.zone.Zone_z0;

    const bucketManager = new qiniu.rs.BucketManager(mac, config);
    const bucket = 'helper-shop';
    // @param options 列举操作的可选参数
    //    prefix    列举的文件前缀
    //    marker    上一次列举返回的位置标记，作为本次列举的起点信息
    //    limit     每次返回的最大列举文件数量
    //    delimiter 指定目录分隔符
    const NODE_ENV = process.env.NODE_ENV;
    const _prefix = NODE_ENV === 'development' ? 'dev-' : 'prod-';
    const options = {
      marker: '',
      limit: 300,
      prefix: _prefix,
    };

    // 获取文章内容
    // const docData = await ctx.model.Admin.ModDoc.find();
    // const docList: any[] = [];
    // const docListName: any[] = [];
    // docData.map((_item: any) => {
    //   docList.push(_item.folder);
    //   docListName.push(_item.title);
    // });

    // 请求七牛文件
    const result = await new Promise((resolve, reject) => {
      bucketManager.listPrefix(bucket, options, (err, respBody, respInfo) => {
        if (err) {
          return reject({
            code: 500,
          });
        }
        if (respInfo.statusCode === 200) {

          // 如果这个nextMarker不为空，那么还有未列举完毕的文件列表，下次调用listPrefix的时候，
          // 指定options里面的marker为这个值
          // const nextMarker = respBody.marker;
          // const commonPrefixes = respBody.commonPrefixes;

          // const items = respBody.items;
          // const array_test: any[] = []; // 暂缓文件夹名使用
          // const array_type: any[] = []; // 返回文件列表
          // items.forEach(item => {
          //   const _item = item.key.split('-')[1];
          //   // 如果存在文件夹
          //   if (array_test.indexOf(_item) < 0) {
          //     array_test.push(_item);
          //     let _class_for = '';
          //     const _item_index = docList.indexOf(_item);
          //     if (_item_index >= 0) {
          //       _class_for = docListName[_item_index];
          //     }
          //     array_type.push({
          //       class_for: _class_for || _item,
          //       class_name: _item,
          //       class_list: [item],
          //     });
          //   } else {
          //     const _index = array_test.indexOf(_item);
          //     array_type[_index].class_list.push(item);
          //   }
          // });

          return resolve({ list: respBody.items });
        }
        return reject({
          code: respInfo.statusCode,
          message: respBody,
        });
      });
    });
    return result;
  }

  // // ======================================================================  删除七牛云文件  ======================================================================
  // async removeFile(params) {
  //   const { ctx } = this;
  //   const _delList = params.delList;

  //   const mac = new qiniu.auth.digest.Mac(ctx.app.config.qiniu.ACCESS_KEY, ctx.app.config.qiniu.SECRET_KEY);
  //   const config = new qiniu.conf.Config();
  //   // config.useHttpsDomain = true;
  //   config.zone = qiniu.zone.Zone_z0;

  //   const bucketManager = new qiniu.rs.BucketManager(mac, config);
  //   const srcBucket = 'helper';

  //   // 删除七牛文件
  //   const result = await new Promise((resolve, reject) => {
  //     const _deleteOperations = [];
  //     // 每个operations的数量不可以超过1000个，如果总数量超过1000，需要分批发送
  //     _delList.map(item => {
  //       _deleteOperations.push(qiniu.rs.deleteOp(srcBucket, item));
  //     });

  //     bucketManager.batch(_deleteOperations, function (err, respBody, respInfo) {
  //       if (err) {
  //         reject(err);
  //       } else {
  //         // 200 is success, 298 is part success
  //         if (parseInt(respInfo.statusCode / 100) == 2) {
  //           respBody.forEach(function (item) {
  //             if (item.code === 200) {
  //               resolve();
  //             } else {
  //               reject(item.code + '\t' + item.data.error);
  //             }
  //           });
  //         } else {
  //           reject(respBody);
  //         }
  //       }
  //     });
  //   });
  //   return result;
  // }
}

module.exports = FilesService;
